<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>

  <script>
    /**
     * 2022年4月28日14:33:26
     * js 37
     * 实现mergePromise函数
     */
    const timer = timer => {
      return new Promise(resolve => {
        setTimeout(() => {
          resolve()
        }, timer)
      })
    }
    const ajax1 = () => timer(2000).then(() => {
      return 1
    })
    const ajax2 = () => timer(2500).then(() => {
      return 2
    })
    const ajax3 = () => timer(1000).then(() => {
      return 3
    })

    function mergePromise(ajaxArr) {
      let data = []
      let promise = Promise.resolve();
      ajaxArr.forEach(ajax => {
        promise = promise.then(ajax).then(value => {
          console.log(value)
          data.push(value)
          return data;
        })
      })
      return promise;
    }

    mergePromise([ajax1, ajax2, ajax3]).then(data => {
      console.log("done");
      console.log(data); // data 为 [1, 2, 3]
    });
  </script>
</body>

</html>
